import pytest
from django.db.utils import IntegrityError
from .models import User, efflog, sysdata, SysLog
from datetime import datetime
from django.test import TestCase, Client
from django.core.files.uploadedfile import SimpleUploadedFile
from unittest.mock import patch, mock_open, MagicMock

class ModelTests(TestCase):
    def setUp(self):
        self.user = User.objects.create(name="testuser", password="password123")
        self.efflog = efflog.objects.create(
            LogID="1",
            LogType="Error",
            OccurTime=datetime.now(),
            SourceIp="127.0.0.1",
            userID=self.user.name,
            Content="Test log content",
            Level="High",
            RelatedID="related1",
            Status=True,
            Handler="handler1",
            HandleTime=datetime.now()
        )
        self.sysdata = sysdata.objects.create(
            CPUusage="50%",
            MEMusage="60%",
            request="testrequest"
        )

    def test_user_creation(self):
        user = User.objects.get(name="testuser")
        self.assertEqual(user.name, "testuser")
        self.assertEqual(user.password, "password123")

    def test_user_password_change(self):
        self.user.password = "newpassword"
        self.user.save()
        self.assertEqual(self.user.password, "newpassword")

    def test_user_name_uniqueness(self):
        with self.assertRaises(IntegrityError):
            User.objects.create(name="testuser", password="anotherpassword")

    def test_efflog_creation(self):
        log = efflog.objects.get(LogID="1")
        self.assertEqual(log.LogType, "Error")
        self.assertEqual(log.SourceIp, "127.0.0.1")
        self.assertEqual(log.userID, self.user.name)
        self.assertEqual(log.Content, "Test log content")
        self.assertEqual(log.Level, "High")
        self.assertEqual(log.RelatedID, "related1")
        self.assertTrue(log.Status)
        self.assertEqual(log.Handler, "handler1")

    def test_efflog_logID_uniqueness(self):
        with self.assertRaises(IntegrityError):
            efflog.objects.create(
                LogID="1",
                LogType="Error",
                OccurTime=datetime.now(),
                SourceIp="127.0.0.1",
                userID=self.user.name,
                Content="Duplicate log content",
                Level="High",
                RelatedID="related1",
                Status=True,
                Handler="handler2",
                HandleTime=datetime.now()
            )

    def test_sysdata_creation(self):
        sysdata_obj = sysdata.objects.get(CPUusage="50%")
        self.assertEqual(sysdata_obj.CPUusage, "50%")
        self.assertEqual(sysdata_obj.MEMusage, "60%")
        self.assertEqual(sysdata_obj.request, "testrequest")

    def test_sysdata_cpuusage_uniqueness(self):
        with self.assertRaises(IntegrityError):
            sysdata.objects.create(
                CPUusage="50%",
                MEMusage="70%",
                request="anotherrequest"
            )

    def test_user_deletion(self):
        self.user.delete()
        with self.assertRaises(User.DoesNotExist):
            User.objects.get(name="testuser")

    def test_sysdata_deletion(self):
        self.sysdata.delete()
        with self.assertRaises(sysdata.DoesNotExist):
            sysdata.objects.get(CPUusage="50%")


class IndexPageTest(TestCase):
    def test_index_page(self):
        response = self.client.get('/index/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'index.html')

    def test_initial_view(self):
        response = self.client.get('/initial/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'initial.html')
        self.assertEqual(self.client.session['automation_level'], 'low')
        self.assertEqual(self.client.session['decision_making'], 'ml_based')
        self.assertEqual(self.client.session['ml_algorithm'], 'SVM')

    def test_aisys_view(self):
        response = self.client.get('/aisys/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'aisys.html')
        self.assertEqual(self.client.session['automation_level'], 'low')
        self.assertEqual(self.client.session['decision_making'], 'ml_based')
        self.assertEqual(self.client.session['ml_algorithm'], 'SVM')

class LoginAction(TestCase):
    def setUp(self) -> None:
        """创建用户数据：两种不同的方式创建用户"""
        User.objects.create(name='admin')
        User.objects.create(name='123456', password='123456')

    def test_add_admin(self):
        """添加用户admin测试"""
        user = User.objects.get(name='admin')
        self.assertEqual(user.name, 'admin')

    def test_add_admin2(self):
        user = User.objects.get(name='123456')
        self.assertEqual(user.name, '123456')
        self.assertEqual(user.password, '123456')

    def test_login_username_password_null(self):
        """用户名密码为空"""
        test_data = {'username': '', 'password': ''}
        response = self.client.post('/login/', data=test_data)
        self.assertTemplateUsed(response, 'login.html')

    def test_mlogin_username_password_null(self):
        """用户名密码为空"""
        test_data = {'username': '', 'password': ''}
        response = self.client.post('/mlogin/', data=test_data)
        self.assertTemplateUsed(response, 'mlogin.html')

    def test_login_view_with_incorrect_password(self):
        # 模拟一个POST请求，其中包含不存在的账号
        test_data = {'username': 'test', 'password': '123456'}
        response = self.client.post('/login/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'login.html')
        storage = response.context['messages']
        messages_list = [msg.message for msg in storage]
        self.assertIn('用户名不正确', messages_list)
        self.assertContains(response, '用户名不正确')

    def test_mlogin_view_with_incorrect_password(self):
        # 模拟一个POST请求，其中包含不存在的账号
        test_data = {'username': 'test', 'password': '123456'}
        response = self.client.post('/mlogin/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'mlogin.html')
        storage = response.context['messages']
        messages_list = [msg.message for msg in storage]
        self.assertIn('管理员用户名不正确', messages_list)
        self.assertContains(response, '管理员用户名不正确')

    def test_login_view_with_incorrect_password1(self):
        # 模拟一个POST请求，其中包含错误的密码
        test_data = {'username': '123456', 'password': '2345'}
        response = self.client.post('/login/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'login.html')
        storage = response.context['messages']
        messages_list = [msg.message for msg in storage]
        self.assertIn('密码不正确', messages_list)
        self.assertContains(response, '密码不正确')

    def test_mlogin_view_with_incorrect_password2(self):
        # 模拟一个POST请求，其中包含错误的密码
        test_data = {'username': '123456', 'password': '2345'}
        response = self.client.post('/mlogin/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'mlogin.html')
        storage = response.context['messages']
        messages_list = [msg.message for msg in storage]
        self.assertIn('管理员密码不正确', messages_list)
        self.assertContains(response, '管理员密码不正确')

    def test_login_action_success(self):
        """登录成功"""
        test_data = {'username': '123456', 'password': '123456'}
        response = self.client.post('/login/', data=test_data)
        self.assertEqual(response.status_code, 302)

    def test_mlogin_action_success(self):
        """登录成功"""
        test_data = {'username': '123456', 'password': '123456'}
        response = self.client.post('/mlogin/', data=test_data)
        self.assertEqual(response.status_code, 302)

class RegisterTest(TestCase):
    def setUp(self):
        User.objects.create(name='admin')
        User.objects.create(name='123456', password='123456')

        self.register_url = '/register/'

    def test_register_page_loads(self):
        response = self.client.get('/register/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'register.html')

    def test_register_with_valid_data(self):
        data = {
            'username': 'testuser',
            'password1': 'password123',
            'password2': 'password123',
        }
        response = self.client.post(self.register_url, data)
        self.assertEqual(response.status_code, 302)  # Check for redirect
        self.assertRedirects(response, '/login/')
        self.assertTrue(User.objects.filter(name='testuser').exists())

    def test_register_with_non_matching_passwords(self):
        data = {
            'username': 'testuser',
            'password1': 'password123',
            'password2': 'differentpassword',
        }
        response = self.client.post(self.register_url, data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'register.html')
        self.assertContains(response, "两次输入的密码不同！")
    def test_register_with_existing_username(self):
        User.objects.create(name='existinguser', password='password123')
        data = {
            'username': 'existinguser',
            'password1': 'password123',
            'password2': 'password123',
        }
        response = self.client.post(self.register_url, data)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, '用户已经存在，请重新选择用户名！')

    def test_register_with_invalid_data(self):
        data = {
            'username': '',
            'password1': '',
            'password2': '',
        }
        response = self.client.post(self.register_url, data)
        self.assertEqual(response.status_code, 200)

class LogoutTest(TestCase):
    def test_logout_view(self):
        response = self.client.get('/logout/')
        self.assertEqual(response.status_code, 302)

class EfflogViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    @patch('MySQLdb.connect')
    def test_efflog_view(self, mock_connect):
        # 设置模拟的数据库返回值
        mock_conn = MagicMock()
        mock_cursor = MagicMock()
        mock_connect.return_value = mock_conn
        mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
        mock_cursor.fetchall.return_value = [
            {'LogID': 1, 'LogType': 'Type1', 'OccurTime': '2021-01-01 00:00:00', 'SourceIP': '127.0.0.1', 'userID': 'user1', 'Content': 'Content1', 'Level': 'Low', 'RelatedID': 1, 'Status': 'Open', 'Handler': 'handler1', 'HandleTime': '2021-01-01 01:00:00'},
            {'LogID': 2, 'LogType': 'Type2', 'OccurTime': '2021-01-02 00:00:00', 'SourceIP': '127.0.0.2', 'userID': 'user2', 'Content': 'Content2', 'Level': 'High', 'RelatedID': 2, 'Status': 'Closed', 'Handler': 'handler2', 'HandleTime': '2021-01-02 01:00:00'}
        ]

        # 发送请求
        response = self.client.get('/efflog/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'efflog.html')
        self.assertIn('efflog', response.context)
        self.assertEqual(len(response.context['efflog']), 2)
        self.assertEqual(response.context['efflog'][0]['LogID'], 1)
        self.assertEqual(response.context['efflog'][1]['LogID'], 2)

class EfflogTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.efflog_url = '/efflog/'

        # Mock the database connection and cursor
        self.mock_conn = MagicMock()
        self.mock_cursor = MagicMock()
        self.mock_conn.cursor.return_value = self.mock_cursor
        self.mock_cursor.__enter__.return_value = self.mock_cursor

    @patch('MySQLdb.connect')
    def test_efflog_page_loads(self, mock_connect):
        mock_connect.return_value = self.mock_conn

        # Set up mock cursor fetchall return value
        self.mock_cursor.fetchall.return_value = [
            {
                "LogID": 1,
                "LogType": "Error",
                "OccurTime": "2024-07-03 12:00:00",
                "SourceIP": "127.0.0.1",
                "userID": 1,
                "Content": "Test log content",
                "Level": "High",
                "RelatedID": 2,
                "Status": "New",
                "Handler": "admin",
                "HandleTime": "2024-07-03 13:00:00"
            }
        ]

        response = self.client.get(self.efflog_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'efflog.html')
        self.assertIn('efflog', response.context)
        self.assertEqual(len(response.context['efflog']), 1)
        self.assertEqual(response.context['efflog'][0]['LogID'], 1)

    @patch('MySQLdb.connect')
    def test_efflog_data_fetch(self, mock_connect):
        mock_connect.return_value = self.mock_conn

        # Set up mock cursor fetchall return value
        self.mock_cursor.fetchall.return_value = [
            {
                "LogID": 1,
                "LogType": "Error",
                "OccurTime": "2024-07-03 12:00:00",
                "SourceIP": "127.0.0.1",
                "userID": 1,
                "Content": "Test log content",
                "Level": "High",
                "RelatedID": 2,
                "Status": "New",
                "Handler": "admin",
                "HandleTime": "2024-07-03 13:00:00"
            },
            {
                "LogID": 2,
                "LogType": "Warning",
                "OccurTime": "2024-07-03 14:00:00",
                "SourceIP": "192.168.1.1",
                "userID": 2,
                "Content": "Another test log content",
                "Level": "Medium",
                "RelatedID": 3,
                "Status": "In Progress",
                "Handler": "user",
                "HandleTime": "2024-07-03 15:00:00"
            }
        ]

        response = self.client.get(self.efflog_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'efflog.html')
        self.assertIn('efflog', response.context)
        self.assertEqual(len(response.context['efflog']), 2)
        self.assertEqual(response.context['efflog'][0]['LogID'], 1)
        self.assertEqual(response.context['efflog'][1]['LogID'], 2)

class CpuViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    @patch('psutil.cpu_count')
    @patch('psutil.cpu_freq')
    def test_cpu_view(self, mock_cpu_freq, mock_cpu_count):
        # 模拟 psutil 和 os 方法的返回值
        mock_cpu_count.side_effect = [14, 20]  # logical cores, physical cores
        mock_cpu_freq.return_value = MagicMock(current='2.3 GHz', min='0', max='2.3 GHz')

        response = self.client.get('/cpu/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'cpu.html')

        # 验证上下文数据
        self.assertIn('logical_core_num', response.context)
        self.assertIn('physical_core_num', response.context)
        self.assertIn('load_avg', response.context)
        self.assertIn('cpu_time_percent', response.context)
        self.assertIn('else_percent', response.context)
        self.assertIn('cpu_freq', response.context)

        self.assertEqual(response.context['logical_core_num'], 14)
        self.assertEqual(response.context['physical_core_num'], 20)
        self.assertEqual(response.context['cpu_freq'].current, '2.3 GHz')
        self.assertEqual(response.context['cpu_freq'].max, '2.3 GHz')
        self.assertEqual(response.context['cpu_freq'].min, '0')

    def test_cpu_view_with_exceptions(self):
        response = self.client.get('/cpu/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'cpu.html')
        self.assertIn('load_avg', response.context)
        self.assertEqual(response.context['load_avg'], ['', '', ''])


class MemoryInfoViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    @patch('psutil.virtual_memory')
    def test_memory_info_view(self, mock_virtual_memory):
        # 模拟 psutil.virtual_memory 方法的返回值
        mock_memory_info = MagicMock(
            total=16849293312,
            available=3085082624,
            percent=50.0,
            used=8000000,
            free=4000000
        )
        mock_virtual_memory.return_value = mock_memory_info

        response = self.client.get('/memory_usage/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'memory_usage.html')
        self.assertIn('memory_info', response.context)
        self.assertEqual(response.context['memory_info'].total, mock_memory_info.total)
        self.assertEqual(response.context['memory_info'].available, mock_memory_info.available)

class RequestCountViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    def test_request_count_view(self):
        response = self.client.get('/request_count/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'request_count.html')
        self.assertIn('request_count', response.context)

class CodeIndexTest(TestCase):
    def codeindextest(self):
        response = self.client.get('/code_evaluate/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'code_evaluate.html')

class SubmitViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    @patch('builtins.open', new_callable=mock_open)
    @patch('os.popen')
    def test_submit_view_with_text_input(self, mock_popen, mock_open):
        mock_popen.return_value.readlines.return_value = ['Your code has been rated at 10.00/10']
        response = self.client.post('/submit/', {'textInput': 'print("Hello, World!")'})
        self.assertEqual(response.status_code, 200)
        mock_open().write.assert_any_call("# -*- coding:utf-8 -*-")
        mock_open().write.assert_any_call('print("Hello, World!")')

        mock_popen.assert_called_once_with('pylint text.py')
        self.assertIn('text_output', response.context)
        self.assertIn('file_output', response.context)
        self.assertIn('code_output', response.context)
        self.assertEqual(response.context['text_output'], 'print("Hello, World!")')
        self.assertEqual(response.context['file_output'], '没有上传任何文件')
        self.assertEqual(response.context['code_output'], 'Your code has been rated at 10.00/10')

    @patch('django.core.files.storage.FileSystemStorage.save')
    @patch('django.core.files.storage.FileSystemStorage.url')
    @patch('os.popen')
    def test_submit_view_with_file_input(self, mock_popen, mock_fs_url, mock_fs_save):
        # 模拟文件系统存储和 os.popen 返回值
        mock_fs_save.return_value = 'test.py'
        mock_fs_url.return_value = '/media/test.py'
        mock_popen.return_value.readlines.return_value = ['Your code has been rated at 10.00/10']

        file = SimpleUploadedFile("test.py", b"print('Hello, World!')", content_type="text/x-python")
        response = self.client.post('/submit/', {'fileInput': file})
        self.assertEqual(response.status_code, 200)
        mock_popen.assert_called_once_with('pylint media/test.py')
        self.assertIn('text_output', response.context)
        self.assertIn('file_output', response.context)
        self.assertIn('code_output', response.context)
        self.assertEqual(response.context['text_output'], None)
        self.assertEqual(response.context['file_output'], '/media/test.py')
        self.assertEqual(response.context['code_output'], 'Your code has been rated at 10.00/10')

    def test_submit_view_get_request(self):
        response = self.client.get('/submit/')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "提交失败，请重试。")

class ManageViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    @patch('MySQLdb.connect')
    def test_manage_view(self, mock_connect):
        # 模拟 MySQL 连接和游标
        mock_conn = MagicMock()
        mock_cursor = MagicMock()
        mock_connect.return_value = mock_conn
        mock_conn.cursor.return_value.__enter__.return_value = mock_cursor

        # 模拟执行查询和返回结果
        mock_cursor.fetchall.side_effect = [
            [
                {'LogID': 1, 'LogType': 'Error', 'OccurTime': '2023-01-01 00:00:00', 'SourceIP': '127.0.0.1',
                 'userID': 'user1', 'Content': 'Error message', 'Level': 'High', 'RelatedID': 'ID1', 'Status': 'Open',
                 'Handler': 'Handler1', 'HandleTime': '2023-01-01 01:00:00'}
            ],
            [
                {'LogID': 1, 'LogType': 'Info', 'OccurTime': '2023-01-01 00:00:00', 'SourceIP': '127.0.0.1',
                 'userID': 'user2', 'Content': 'Info message', 'Level': 'Low', 'RelatedID': 'ID2', 'Status': 'Closed',
                 'Handler': 'Handler2', 'HandleTime': '2023-01-01 01:00:00'}
            ]
        ]

        response = self.client.get('/manage/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'manage.html')
        self.assertIn('efflog', response.context)
        self.assertIn('syslog', response.context)
        self.assertEqual(len(response.context['efflog']), 1)
        self.assertEqual(len(response.context['syslog']), 1)
        self.assertEqual(response.context['efflog'][0]['LogType'], 'Error')
        self.assertEqual(response.context['syslog'][0]['LogType'], 'Info')
        self.assertEqual(mock_cursor.execute.call_count, 2)
        mock_cursor.execute.assert_any_call(
            "SELECT LogID,LogType,OccurTime,SourceIP,userID,Content,Level,RelatedID,Status,Handler,HandleTime FROM sims_efflog")
        mock_cursor.execute.assert_any_call("SELECT * FROM syslog LIMIT 1000")

class LogDelSysDelViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    @patch('MySQLdb.connect')
    def test_logdel_view(self, mock_connect):
        mock_conn = MagicMock()
        mock_cursor = MagicMock()
        mock_connect.return_value = mock_conn
        mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
        response = self.client.get('/logdel/', {'LogID': 1})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, "/manage/")
        mock_conn.commit.assert_called_once()

    @patch('MySQLdb.connect')
    def test_sysdel_view(self, mock_connect):
        # 模拟 MySQL 连接和游标
        mock_conn = MagicMock()
        mock_cursor = MagicMock()
        mock_connect.return_value = mock_conn
        mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
        response = self.client.get('/sysdel/', {'LogID': 1})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, "/manage/")
        mock_conn.commit.assert_called_once()

class SysDataViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    def test_edit_view(self):
        response = self.client.get('/edit/', {'CPUusage': '50'})
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/sysdata/')

    def test_limit_view(self):
        response = self.client.get('/limit/', {'MEMusage': '75'})
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/sysdata/')

    def test_unlockCPU_view(self):
        response = self.client.get('/unlockCPU/', {'CPUusage': '30'})
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/sysdata/')

    def test_unlockMEM_view(self):
        response = self.client.get('/unlockMEM/', {'MEMusage': '80'})
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/sysdata/')

class ControlViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.url = '/control/'

    def test_control_view_get(self):
        # 测试 GET 请求
        session = self.client.session
        session['automation_level'] = 'medium'
        session['decision_making'] = 'Bayes'
        session['ml_algorithm'] = 'some_algorithm'
        session.save()

        response = self.client.get(self.url)

        # 验证返回状态码
        self.assertEqual(response.status_code, 200)

        # 验证使用的模板
        self.assertTemplateUsed(response, 'control.html')

        # 验证上下文数据
        self.assertEqual(response.context['automation_level'], 'medium')
        self.assertEqual(response.context['decision_making'], 'Bayes')
        self.assertEqual(response.context['ml_algorithm'], 'some_algorithm')
        self.assertEqual(response.context['a'], '中智能化力度')
        self.assertEqual(response.context['b'], '朴素贝叶斯算法')
        self.assertEqual(response.context['c'], '正在使用机器学习决策算法')

    def test_control_view_post(self):
        # 测试 POST 请求
        post_data = {
            'automation_level': 'high',
            'decision_making': 'SVM',
            'ml_algorithm': 'new_algorithm'
        }
        response = self.client.post(self.url, post_data)

        # 验证返回状态码和重定向
        self.assertEqual(response.status_code, 200)

        # 验证消息
        messages = list(response.wsgi_request._messages)
        self.assertEqual(len(messages), 1)
        self.assertEqual(messages[0].message, '设置成功')
        self.assertEqual(messages[0].level, 25)  # 25 corresponds to success level

        # 验证会话数据
        session = self.client.session
        self.assertEqual(session['automation_level'], 'high')
        self.assertEqual(session['decision_making'], 'SVM')
        self.assertEqual(session['ml_algorithm'], 'new_algorithm')

        # 验证上下文数据
        self.assertEqual(response.context['automation_level'], 'high')
        self.assertEqual(response.context['decision_making'], 'SVM')
        self.assertEqual(response.context['ml_algorithm'], 'new_algorithm')
        self.assertEqual(response.context['a'], '高智能化力度')
        self.assertEqual(response.context['b'], '支持向量机算法')
        self.assertEqual(response.context['c'], '正在使用机器学习决策算法')


class SDViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.url = '/sysdata/'

    @patch('sims.views.psutil.cpu_percent')
    @patch('sims.views.psutil.virtual_memory')
    @patch('sims.views.psutil.disk_usage')
    @patch('sims.views.load')
    @patch('sims.views.MySQLdb.connect')
    def test_sysdata_view(self, mock_connect, mock_load, mock_disk_usage, mock_virtual_memory, mock_cpu_percent):
        # Mock MySQL connection and cursor
        mock_conn = MagicMock()
        mock_cursor = MagicMock()
        mock_connect.return_value = mock_conn
        mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
        mock_cursor.fetchall.return_value = [
            {'CPUusage': '20', 'MEMusage': '30', 'request': '50'}
        ]
        mock_cpu_percent.return_value = 50
        mock_virtual_memory.return_value.percent = 60
        mock_disk_usage.return_value.percent = 70
        random_network = 20
        random_temp = 60
        with patch('random.randint', side_effect=[random_network, random_temp]):
            session = self.client.session
            session['automation_level'] = 'medium'
            session['decision_making'] = 'Bayes'
            session['ml_algorithm'] = 'Bayes'
            session.save()
            mock_model = MagicMock()
            mock_vectorizer = MagicMock()
            mock_load.side_effect = [mock_model, mock_vectorizer]
            mock_model.predict.return_value = ['High CPU and memory usage causing system slowdowns.']
            response = self.client.get(self.url)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, 'sysdata.html')
            self.assertEqual(response.context['cpu'], 50)
            self.assertEqual(response.context['memory'], 60)
            self.assertEqual(response.context['disk'], 70)
            self.assertEqual(response.context['network'], random_network)
            self.assertEqual(response.context['temp'], random_temp)
            self.assertEqual(response.context['automation_level'], 'medium')
            self.assertEqual(response.context['decision_making'], 'Bayes')
            self.assertEqual(response.context['ml_algorithm'], 'Bayes')

    @patch('sims.views.psutil.cpu_percent')
    @patch('sims.views.psutil.virtual_memory')
    @patch('sims.views.psutil.disk_usage')
    @patch('sims.views.load')
    @patch('sims.views.MySQLdb.connect')
    def test_sysdata_view_svm(self, mock_connect, mock_load, mock_disk_usage, mock_virtual_memory, mock_cpu_percent):
        mock_conn = MagicMock()
        mock_cursor = MagicMock()
        mock_connect.return_value = mock_conn
        mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
        mock_cursor.fetchall.return_value = [
            {'CPUusage': '20', 'MEMusage': '30', 'request': '50'}
        ]
        mock_cpu_percent.return_value = 50
        mock_virtual_memory.return_value.percent = 60
        mock_disk_usage.return_value.percent = 70
        random_network = 20
        random_temp = 60
        with patch('random.randint', side_effect=[random_network, random_temp]):
            session = self.client.session
            session['automation_level'] = 'medium'
            session['decision_making'] = 'SVM'
            session['ml_algorithm'] = 'SVM'
            session.save()
            mock_model = MagicMock()
            mock_label_encoder = MagicMock()
            mock_load.side_effect = [mock_model, mock_label_encoder]
            mock_model.predict.return_value = [0]
            mock_label_encoder.inverse_transform.return_value = ['High CPU and disk usage may lead to performance degradation.']
            response = self.client.get(self.url)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, 'sysdata.html')
            self.assertEqual(response.context['cpu'], 50)
            self.assertEqual(response.context['memory'], 60)
            self.assertEqual(response.context['disk'], 70)
            self.assertEqual(response.context['network'], random_network)
            self.assertEqual(response.context['temp'], random_temp)
            self.assertEqual(response.context['automation_level'], 'medium')
            self.assertEqual(response.context['decision_making'], 'SVM')
            self.assertEqual(response.context['ml_algorithm'], 'SVM')

class ViewsTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create(name='123456', password='123456')

    def test_index_view(self):
        response = self.client.get('/index/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'index.html')

    def test_initial_view(self):
        response = self.client.get('/initial/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.client.session['automation_level'], 'low')
        self.assertEqual(self.client.session['decision_making'], 'ml_based')
        self.assertEqual(self.client.session['ml_algorithm'], 'SVM')
        self.assertTemplateUsed(response, 'initial.html')

    def test_aisys_view(self):
        response = self.client.get('/aisys/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.client.session['automation_level'], 'low')
        self.assertEqual(self.client.session['decision_making'], 'ml_based')
        self.assertEqual(self.client.session['ml_algorithm'], 'SVM')
        self.assertTemplateUsed(response, 'aisys.html')

    def test_login_view(self):
        response = self.client.post('/login/', {'username': '123456', 'password': '123456'})
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/aisys/')

    def test_logout_view(self):
        self.client.login(username='123456', password='123456')
        response = self.client.get('/logout/')
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/index/')

    def test_manage_view(self):
        self.client.login(username='123456', password='123456')
        response = self.client.get('/manage/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'manage.html')
    def test_control_view(self):
        self.client.login(username='123456', password='123456')
        response = self.client.post('/control/', {'automation_level': 'medium', 'decision_making': 'Bayes', 'ml_algorithm': 'DecisionTree'})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.client.session['automation_level'], 'medium')
        self.assertEqual(self.client.session['decision_making'], 'Bayes')
        self.assertEqual(self.client.session['ml_algorithm'], 'DecisionTree')
        self.assertTemplateUsed(response, 'control.html')

if __name__ == '__main__':
    pytest.main()